package com.neusoft.newelm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.newelm.bean.Admin;
import com.neusoft.newelm.bean.Role;
import com.neusoft.newelm.bean.RoleAdmin;
import com.neusoft.newelm.common.ElmException;
import com.neusoft.newelm.mapper.AdminMapper;
import com.neusoft.newelm.mapper.RoleAdminMapper;
import com.neusoft.newelm.mapper.RoleMapper;
import com.neusoft.newelm.service.AdminService;
import com.neusoft.newelm.service.RoleService;

/**
 * 
 * @author chens
 *
 */
@Service
@Transactional(rollbackFor = ElmException.class)
public class AdminServiceImpl extends DefaultServiceImpl<Admin> implements AdminService {

	@Autowired
	private AdminMapper adminMapper;

	@Autowired
	private RoleAdminMapper roleAdminMapper;

	@Override
	public Admin login(Admin admin) {

		Admin ret = null;

		try {
			ret = adminMapper.login(admin);
		} catch (Exception e) {
			throw new ElmException("登录异常", e);
		}
		return ret;
	}

	@Override
	public boolean deleteById(Integer id) {
		boolean ret = false;

		if (id == 1) {
			throw new ElmException("超级帐号不能删除");
		} else {
			try {
				// 注意必须使用super进行调用，避免死循环
				// 先删除管理员的角色，再删除管理员信息
				roleAdminMapper.deleteByAdmin(new Admin(id, null, null));
				
				ret =super.deleteById(id);

			} catch (RuntimeException e) {
				throw new ElmException("删除管理员失败", e);
			}
		}

		return ret;
	}

	@Override
	public boolean add(Admin object) {
		boolean ret = false;

		// 多表关联数据更新，经常会操作多个表格，这组操作构成一个事务；
		try {
			ret = adminMapper.add(object);
			if (ret) {
				List<Role> list = object.getRoles();
				for (Role role : list) {
					ret &= roleAdminMapper.add(new RoleAdmin(null, role.getId(), object.getAdminId()));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ElmException("新增管理员或分配角色异常");
		}

		return ret;
	}

	@Override
	public boolean edit(Admin object) {
		boolean ret = false;
		// 修改密码和盐
		try {
			ret = super.edit(object);
			// 修改角色- 先删除后新增(可以编写其它逻辑进行功能实现： 先判断再删除和新增)
			ret &= roleAdminMapper.deleteByAdmin(object);
			List<Role> list = object.getRoles();
			for (Role role : list) {
				ret &= roleAdminMapper.add(new RoleAdmin(null, role.getId(), object.getAdminId()));
			}
		} catch (RuntimeException e) {
			throw new ElmException("修改密码或角色异常");
		}

		return ret;
	}

}
